/**
 * @author sheyifan 2020-11-22 20:32
 * @copyright wingtech.sheyifan
 * @description for operating dom
 */

 /**
  * 2020-11-22 20:35 sheyifan Issue: fill modal on clicking each table row
  */
function fillModalOnClickTableRow() {
    /** @type {NodeListOf<HTMLTableRowElement>} */
    let tableRows = document.querySelectorAll("tbody tr")
    for (let tableRow of tableRows) {
        tableRow.addEventListener('click', (mouseEvent) => {
            fillOnShown(tableRow)
        })
    }
}

function fillModalDate() {
    $('#myModal').on('shown.bs.modal', fill())

    /**
     * 2020-11-03 19:21 sheyifan Issue: fill date on modal
     */
    function fill() {
        /** @type {HTMLInputElement} */
        let dateInput = document.querySelector("#myModal input[type='date']");
        /** @type {HTMLInputElement} */
        let dateInput1 = document.querySelector("#appoint input[type='date']");

        /** @type {string} */
        let currentDate = document.querySelector("#current-date").value
        dateInput.value = currentDate
        dateInput1.value = currentDate

        /** @type {HTMLButtonElement} */
        let createButton = document.querySelectorAll("#myModal .create-issue").item(0)
        if (createButton != null) {
            createButton.addEventListener('click', (mouseEvent) => {
                /** @type {HTMLSelectElement} */
                let prioritySelector = document.querySelector("#myModal select[name='priority']")
                /** @type {HTMLInputElement} */
                let todoInput = document.querySelector("#myModal input[name='todo']")
                /** @type {HTMLInputElement} */
                let todoDescInput = document.querySelector("#myModal input[name='description']")
                /** @type {HTMLSelectElement} */
                let labelsMultiSelector = document.querySelector("#myModal select[name='labels']")
                /** @type {HTMLInputElement} */
                let riskInput = document.querySelector("#myModal input[name='risk']")
                /** @type {HTMLInputElement} */
                let assertsInput = document.querySelector("#myModal input[name='asserts']")
                /** @type {HTMLInputElement} */
                let stateInput = document.querySelector("#myModal input[name='state']")
                /** @type {HTMLInputElement} */
                let finishDescInput = document.querySelector("#myModal input[name='finish-description']")

                require('./issue').createIssue({
                    日期: new Date(currentDate),
                    待办: todoInput.value,
                    优先级: getSelectedFromSelector(prioritySelector)[0],
                    保密: false,
                    事项说明: todoDescInput.value,
                    标签: getSelectedFromSelector(labelsMultiSelector),
                    风险: riskInput.value,
                    完成状态: Number.parseFloat(stateInput.value),
                    完成说明: finishDescInput.value,
                    资源求助: assertsInput.value
                }, "now")
                document.location.reload()
            })
        }

        /** @type {HTMLButtonElement} */
        let appointButton = document.querySelectorAll("#appoint .appoint-issue").item(0)
        if (appointButton != null) {
            appointButton.addEventListener('click', (mouseEvent) => {
                /** @type {HTMLSelectElement} */
                let prioritySelector = document.querySelector("#appoint select[name='priority']")
                /** @type {HTMLInputElement} */
                let todoInput = document.querySelector("#appoint input[name='todo']")
                /** @type {HTMLInputElement} */
                let todoDescInput = document.querySelector("#appoint input[name='description']")
                /** @type {HTMLSelectElement} */
                let labelsMultiSelector = document.querySelector("#appoint select[name='labels']")
                /** @type {HTMLInputElement} */
                let riskInput = document.querySelector("#appoint input[name='risk']")
                /** @type {HTMLInputElement} */
                let assertsInput = document.querySelector("#appoint input[name='asserts']")
                /** @type {HTMLInputElement} */
                let stateInput = document.querySelector("#appoint input[name='state']")
                /** @type {HTMLInputElement} */
                let finishDescInput = document.querySelector("#appoint input[name='finish-description']")

                require('./issue').createIssue({
                    日期: new Date(currentDate),
                    待办: todoInput.value,
                    优先级: getSelectedFromSelector(prioritySelector)[0],
                    保密: false,
                    事项说明: todoDescInput.value,
                    标签: getSelectedFromSelector(labelsMultiSelector),
                    风险: riskInput.value,
                    完成状态: Number.parseFloat(stateInput.value),
                    完成说明: finishDescInput.value,
                    资源求助: assertsInput.value
                }, "appointed")
                document.location.reload()
            })
        }
    }
}

/**
 * 2020-11-22 17:14 sheyifan Issue: fill modal on clicking table row
 * @param {HTMLTableRowElement} row table row which was clicked to trigger modal
 */
function fillOnShown(row) {
    // 2020-11-22 13:24 sheyifan Issue: fill modal on clicking table rows
    $('#rud').on('shown.bs.modal', fill())

    /**
     * 2020-11-25 19:48 sheyifan Issue: fill modal on clicking table rows
     */
    function fill() {
        /** @type {HTMLInputElement} */
        let dateInput = document.querySelector("#rud input[type='date']");
        /** @type {HTMLSelectElement} */
        let prioritySelector = document.querySelector("#rud select[name='priority']")
        /** @type {HTMLInputElement} */
        let todoInput = document.querySelector("#rud input[name='todo']")
        /** @type {HTMLInputElement} */
        let todoDescInput = document.querySelector("#rud input[name='description']")
        /** @type {HTMLSelectElement} */
        let labelsMultiSelector = document.querySelector("#rud select[name='labels']")
        /** @type {HTMLInputElement} */
        let riskInput = document.querySelector("#rud input[name='risk']")
        /** @type {HTMLInputElement} */
        let assertsInput = document.querySelector("#rud input[name='asserts']")
        /** @type {HTMLInputElement} */
        let stateInput = document.querySelector("#rud input[name='state']")
        /** @type {HTMLInputElement} */
        let finishDescInput = document.querySelector("#rud input[name='finish-description']")

        let currentDate = document.querySelector("#current-date").value
        /** @type {NodeListOf<HTMLTableCellElement>} */
        let issueInfos = row.querySelectorAll("td")
        let issueItems = new IssueItems({
            priority: issueInfos.item(0).innerHTML,
            todo: issueInfos.item(1).innerHTML,
            todoDesc: issueInfos.item(2).innerHTML,
            labels: issueInfos.item(3).innerHTML.split(','),
            risk: issueInfos.item(4).innerHTML,
            asserts: issueInfos.item(5).innerHTML,
            state: Number.parseFloat(issueInfos.item(6).innerHTML),
            finishDesc: issueInfos.item(7).innerHTML
        })

        dateInput.value = currentDate
        switch (issueItems.priority) {
            case "T0":
                prioritySelector.selectedIndex = 0
                break;
            case "T1":
                prioritySelector.selectedIndex = 1
                break;
            case "T2":
                prioritySelector.selectedIndex = 2
                break;
        }
        todoInput.value = issueItems.todo
        todoDescInput.value = issueItems.todoDesc

        // 2020-11-23 sheyifan Issue: iterate labels in table row and select corresponding options
        // in selector of modal
        for (let label of issueItems.labels) {
            let containsFlag = false
            let optionIndex = 0

            for (optionIndex = labelsMultiSelector.options.length - 1 ; optionIndex >= 0  ; optionIndex--) {
                if (labelsMultiSelector.options.item(optionIndex).innerHTML === label) {
                    containsFlag = true
                    break
                }
                else {
                    labelsMultiSelector.options.item(optionIndex).selected = false
                }
            }

            if (containsFlag) {
                labelsMultiSelector.options.item(optionIndex).selected = true
            }
        }

        riskInput.value = issueItems.risk
        assertsInput.value = issueItems.asserts
        stateInput.value = issueItems.state
        finishDescInput.value = issueItems.finishDesc

        /** @type {HTMLButtonElement} */
        let deleteButton = document.querySelectorAll("#rud .remove-issue").item(0)
        if (deleteButton != null && deleteButton != undefined) {
            deleteButton.addEventListener('click', (mouseEvent) => {
                require('./issue').deleteIssue({
                    日期: new Date(currentDate),
                    待办: issueItems.todo,
                    事项说明: issueItems.todoDesc,
                    优先级: issueItems.priority
                })
                document.location.reload()
            })
        }
        else {
            console.log("Cannot find button for deleting issue from data files.")
        }

        /** @type {HTMLButtonElement} */
        let updateButton = document.querySelectorAll("#rud .update-issue").item(0)
        if (updateButton != null) {
            updateButton.addEventListener('click', (mouseEvent) => {
                require('./issue').updateIssue({
                    日期: new Date(currentDate),
                    待办: issueItems.todo,
                    事项说明: issueItems.todoDesc
                },{
                    待办: todoInput.value,
                    优先级: getSelectedFromSelector(prioritySelector)[0],
                    保密: false,
                    事项说明: todoDescInput.value,
                    标签: getSelectedFromSelector(labelsMultiSelector),
                    风险: riskInput.value,
                    完成状态: Number.parseFloat(stateInput.value),
                    完成说明: finishDescInput.value,
                    资源求助: assertsInput.value
                })
                document.location.reload()
            })
        }
    }
}

class IssueItems {
    /**
     * 2020-11-23 sheyifan Issue: create a class for packing data of a issue
     * @param {{
     *     priority: string,
     *     todo: string,
     *     todoDesc: string,
     *     labels: string[],
     *     risk: string,
     *     asserts: string,
     *     state: number,
     *     finishDesc: string
     * }} issueItems 
     */
    constructor(issueItems) {
        this.priority = issueItems.priority
        this.todo = issueItems.todo
        this.todoDesc = issueItems.todoDesc
        this.labels = issueItems.labels
        this.risk = issueItems.risk
        this.asserts = issueItems.asserts
        this.state = issueItems.state
        this.finishDesc = issueItems.finishDesc
    }
}

/**
 * 2020-11-26 sheyifan Issue: get selected items from <select>
 * @param {HTMLSelectElement} selector 
 * @returns {string[]}
 */
function getSelectedFromSelector(selector) {
    /** @type {string[]} */
    let selected = []

    for (let option of selector.options) {
        if (option.selected) {
            selected.push(option.innerHTML)
        }
    }

    return selected
}

/**
 * 2020-11-22 15:13 sheyifan Issue: iterate HTML selector
 * @param {HTMLSelectElement} selector 
 */
function iterateSelector(selector) {
    for (let i = 0 ; i < selector.options.length ; i++) {
        let option = selector.options[i]
        console.log(option)
    }
}

module.exports = {
    fillModalOnClickTableRow,
    fillModalDate
}